package org.esprit.ocm.client.ui.one;

import java.util.List;

import org.esprit.ocm.client.model.oca.datasource.ImageLocalDS;
import org.esprit.ocm.client.rpc.oca.ImageOcaService;
import org.esprit.ocm.client.rpc.oca.ImageOcaServiceAsync;
import org.esprit.ocm.dto.impl.AwsCredentialsDto;
import org.esprit.ocm.dto.impl.ServerDto;
import org.esprit.ocm.dto.impl.UserDto;
import org.esprit.ocm.model.oca.ImageOca;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.types.VisibilityMode;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Button;
import com.smartgwt.client.widgets.Img;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.events.RecordClickEvent;
import com.smartgwt.client.widgets.grid.events.RecordClickHandler;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.SectionStack;
import com.smartgwt.client.widgets.layout.SectionStackSection;
import com.smartgwt.client.widgets.menu.Menu;
import com.smartgwt.client.widgets.menu.MenuItem;
import com.smartgwt.client.widgets.menu.events.MenuItemClickEvent;
import com.smartgwt.client.widgets.toolbar.ToolStrip;
import com.smartgwt.client.widgets.toolbar.ToolStripMenuButton;
import com.smartgwt.client.widgets.viewer.DetailViewer;
import com.smartgwt.client.widgets.viewer.DetailViewerField;

public class ImageZone extends SectionStack {

	private final ImageOcaServiceAsync	imageOcaService	= GWT.create(ImageOcaService.class);

	private DataSource					ds;
	private ListGrid					grid;
	private DetailViewer				details;
	private DetailViewer				detailsTemplate;

	public ImageZone(final ServerDto server, final AwsCredentialsDto credentials, final UserDto user) {

		getData(server, credentials);

		// creer imageSection
		SectionStackSection imageSection = new SectionStackSection("Images List");
		imageSection.setExpanded(true);
		addSection(imageSection);

		// creer imageGrid
		grid = new ListGrid();
		setVisibilityMode(VisibilityMode.MULTIPLE);
		setHeaderHeight(20);
		grid.setShowFilterEditor(true);
		grid.setFilterOnKeypress(true);
		grid.setAutoFetchData(true);

		// creer imagetoolstrip
		ToolStrip imageGridToolStrip = new ToolStrip();
		imageGridToolStrip.setWidth100();
		imageGridToolStrip.addFill();

		// ajouter toolstrip a instanceSection
		imageSection.addItem(imageGridToolStrip);

		// creer filterButton
		final Button filterButton = new Button("Filter");
		filterButton.setShowRollOver(true);
		filterButton.setShowDown(true);
		filterButton.setIcon("filter.png");
		filterButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				grid.setShowFilterEditor(true);
				grid.setFilterOnKeypress(true);
				filterButton.addClickHandler(new ClickHandler() {

					public void onClick(ClickEvent event) {
						grid.setShowFilterEditor(false);

					}
				});
			}
		});

		/**
		 * Attribute Button menu
		 */
		Menu menuAttribute = new Menu();
		menuAttribute.setShowShadow(true);
		menuAttribute.setShadowDepth(10);

		MenuItem newAttributeItem = new MenuItem("Add");
		newAttributeItem.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler() {

			public void onClick(MenuItemClickEvent event) {
				// TODO popup
			}
		});
		MenuItem removeAttributeItem = new MenuItem("Remove");
		removeAttributeItem.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler() {

			public void onClick(MenuItemClickEvent event) {
				// TODO popup
			}
		});

		MenuItem updateAttributeItem = new MenuItem("Update");
		updateAttributeItem.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler() {

			public void onClick(MenuItemClickEvent event) {
				// TODO popup
			}
		});

		menuAttribute.setItems(newAttributeItem, removeAttributeItem, updateAttributeItem);

		final ToolStripMenuButton menuAttributeButton = new ToolStripMenuButton("Attribute", menuAttribute);
		menuAttributeButton.disable();

		/**
		 * Image Button menu
		 */
		Menu menuImage = new Menu();
		menuImage.setShowShadow(true);
		menuImage.setShadowDepth(10);

		MenuItem enableImageItem = new MenuItem("Enable");
		enableImageItem.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler() {

			public void onClick(MenuItemClickEvent event) {

				String secret = credentials.getAwsAccessKeyId() + ":" + credentials.getSecretAccessKey();
				String endpoint = server.getIpServer();

				int imgId = Integer.parseInt(grid.getSelectedRecord().getAttribute("id"));

				imageOcaService.enable(secret, endpoint, imgId, new AsyncCallback<String>() {

					public void onSuccess(String s) {
						SC.warn(s);
						ds.destroy();
						getData(server, credentials);
						grid.redraw();
					}

					public void onFailure(Throwable caught) {

					}
				});
			}
		});

		MenuItem disableImageItem = new MenuItem("Disable");
		disableImageItem.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler() {

			public void onClick(MenuItemClickEvent event) {

				String secret = credentials.getAwsAccessKeyId() + ":" + credentials.getSecretAccessKey();
				String endpoint = server.getIpServer();

				int imgId = Integer.parseInt(grid.getSelectedRecord().getAttribute("id"));

				imageOcaService.disable(secret, endpoint, imgId, new AsyncCallback<String>() {

					public void onSuccess(String s) {
						SC.warn(s);
						ds.destroy();
						getData(server, credentials);
						grid.redraw();
					}

					public void onFailure(Throwable caught) {

					}
				});
			}
		});

		MenuItem publishImageItem = new MenuItem("Publish");
		publishImageItem.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler() {

			public void onClick(MenuItemClickEvent event) {

				String secret = credentials.getAwsAccessKeyId() + ":" + credentials.getSecretAccessKey();
				String endpoint = server.getIpServer();

				int imgId = Integer.parseInt(grid.getSelectedRecord().getAttribute("id"));

				imageOcaService.publish(secret, endpoint, imgId, new AsyncCallback<String>() {

					public void onSuccess(String s) {
						SC.warn(s);
						ds.destroy();
						getData(server, credentials);
						grid.redraw();
					}

					public void onFailure(Throwable caught) {

					}
				});
			}
		});

		MenuItem unpublishImageItem = new MenuItem("Unpublish");
		unpublishImageItem.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler() {

			public void onClick(MenuItemClickEvent event) {

				String secret = credentials.getAwsAccessKeyId() + ":" + credentials.getSecretAccessKey();
				String endpoint = server.getIpServer();

				int imgId = Integer.parseInt(grid.getSelectedRecord().getAttribute("id"));

				imageOcaService.unpublish(secret, endpoint, imgId, new AsyncCallback<String>() {

					public void onSuccess(String s) {
						SC.warn(s);
						ds.destroy();
						getData(server, credentials);
						grid.redraw();
					}

					public void onFailure(Throwable caught) {

					}
				});
			}
		});

		menuImage.setItems(enableImageItem, disableImageItem, publishImageItem, unpublishImageItem);

		final ToolStripMenuButton menuImageButton = new ToolStripMenuButton("Image", menuImage);
		menuImageButton.disable();

		/**
		 * Image button
		 */
		final Button imageButton = new Button("New");
		imageButton.setShowRollOver(true);
		imageButton.setShowDown(true);
		imageButton.setIcon("add.png");
		imageButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {

				CreateImage createImage = new CreateImage(server, credentials, user);
				createImage.show(); 
			}
		});

		final Button refreshButton = new Button("Refresh");
		refreshButton.setShowRollOver(true);
		refreshButton.setShowDown(true);
		refreshButton.setIcon("interact.png");
		refreshButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				SC.say("Refreshed");
				ds.destroy();
				getData(server, credentials);
				grid.redraw();
			}
		});

		final Button deleteButton = new Button("Delete");
		deleteButton.setShowRollOver(true);
		deleteButton.disable();
		deleteButton.setShowDown(true);
		deleteButton.setIcon("remove.png");
		deleteButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {

				String secret = credentials.getAwsAccessKeyId() + ":" + credentials.getSecretAccessKey();
				String endpoint = server.getIpServer();

				int imgId = Integer.parseInt(grid.getSelectedRecord().getAttribute("id"));

				imageOcaService.delete(secret, endpoint, imgId, new AsyncCallback<String>() {

					public void onSuccess(String s) {
						SC.warn(s);
						ds.destroy();
						getData(server, credentials);
						grid.redraw();
					}

					public void onFailure(Throwable caught) {

					}
				});
			}
		});
		
		Img filter = new Img("filter.png", 15, 15);

		// creer filterButton
		final Button filterButtonOn = new Button("On");
		filterButtonOn.setWidth(25);
		filterButtonOn.setHeight(20);
		filterButtonOn.setShowRollOver(true);
		filterButtonOn.setShowDown(true);
		// filterButtonOn.setIcon("filter.png");
		filterButtonOn.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {

				grid.setShowFilterEditor(true);
				grid.setFilterOnKeypress(true);
			}
		});
		// creer filterButton
		final Button filterButtonOff = new Button("Off");
		filterButtonOff.setWidth(25);
		filterButtonOff.setHeight(20);
		filterButtonOff.setShowRollOver(true);
		filterButtonOff.setShowDown(true);
		// filterButtonOff.setIcon("filter.png");
		filterButtonOff.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {

				grid.setShowFilterEditor(false);
				grid.setFilterOnKeypress(false);
			}
		});

		// ajouter le bouton
		imageGridToolStrip.addMember(imageButton);
		imageGridToolStrip.addMember(deleteButton);
		// imageGridToolStrip.addSpacer(30);
		// imageGridToolStrip.addMember(menuAttributeButton);
		imageGridToolStrip.addSpacer(30);
		imageGridToolStrip.addMember(menuImageButton);
		imageGridToolStrip.addSpacer(30);
		imageGridToolStrip.addMember(refreshButton);
		imageGridToolStrip.addSpacer(10);
		imageGridToolStrip.addMember(filter);
		imageGridToolStrip.addSpacer(2);
		imageGridToolStrip.addMember(filterButtonOn);
		imageGridToolStrip.addMember(filterButtonOff);
		imageGridToolStrip.addSpacer(5);

		// ajouter instanceGrid a instanceSection
		imageSection.addItem(grid);

		// creer DetailinstanceSection

		details = new DetailViewer();
		details.setWidth100();
		details.setMargin(15);
		details.setEmptyMessage("Select something to view its details");

		detailsTemplate = new DetailViewer();
		detailsTemplate.setWidth100();
		detailsTemplate.setMargin(15);
		detailsTemplate.setEmptyMessage("Select something to view its details");

		grid.addRecordClickHandler(new RecordClickHandler() {

			public void onRecordClick(RecordClickEvent event) {

				details.setData(new Record[] { event.getRecord() });
				detailsTemplate.setData(new Record[] { event.getRecord() });

				deleteButton.enable();
				menuImageButton.enable();
				menuAttributeButton.enable();
			}
		});

		HLayout viewDetail = new HLayout();
		viewDetail.setHeight("30%");
		viewDetail.setPadding(5);

		viewDetail.addMember(details);
		viewDetail.addMember(detailsTemplate);

		SectionStackSection imageDetailSection = new SectionStackSection("Image Detail");
		imageDetailSection.setExpanded(true);
		imageDetailSection.setResizeable(true);
		imageDetailSection.addItem(viewDetail);
		addSection(imageDetailSection);

		// draw();
	}

	private void getData(ServerDto server, AwsCredentialsDto credentials) {

		String secret = credentials.getAwsAccessKeyId() + ":" + credentials.getSecretAccessKey();
		String endpoint = server.getIpServer();
		/**
		 * Possible values:
		 * <ul>
		 * <li><= -2: All Images</li>
		 * <li>-1: Connected user's Images</li>
		 * <li>>=0: UID User's VMs</li>
		 * </ul>
		 */
		// FIXME le graphique avec le filtre
		int filter = -2;
		imageOcaService.listAll(secret, endpoint, filter, new AsyncCallback<List<ImageOca>>() {

			public void onSuccess(List<ImageOca> list) {

				for (ImageOca imageOca : list) {
					System.out.println("++" + imageOca.getUsername());
				}
				
				ds = new DataSource();
				ds = ImageLocalDS.getInstance(list);

				grid.setDataSource(ds);
				details.setDataSource(ds);
				detailsTemplate.setDataSource(ds);

				ListGridField idField = new ListGridField("id");
				ListGridField uid = new ListGridField("uid");
//				ListGridField username = new ListGridField("username");
				ListGridField name = new ListGridField("name");
				ListGridField type = new ListGridField("type");
				ListGridField publicState = new ListGridField("publicState");
				ListGridField persistent = new ListGridField("persistent");
				ListGridField regtime = new ListGridField("regtime");
				ListGridField source = new ListGridField("source");
				ListGridField state = new ListGridField("state");
				ListGridField running_vms = new ListGridField("running_vms");

				grid.setFields(idField, uid, name, type, publicState, persistent, regtime, source, state, running_vms);

				DetailViewerField templateOca_dev_prefix = new DetailViewerField("templateOca_dev_prefix", "templateOca_dev_prefix");
				DetailViewerField templateOca_name = new DetailViewerField("templateOca_name", "templateOca_name");
				DetailViewerField templateOca_path = new DetailViewerField("templateOca_path", "templateOca_path");
				DetailViewerField templateOca_type = new DetailViewerField("templateOca_type", "templateOca_type");

				detailsTemplate.setFields(templateOca_dev_prefix, templateOca_name, templateOca_path, templateOca_type);

				DetailViewerField idFieldDetail = new DetailViewerField("id", "id");
				DetailViewerField uidDetail = new DetailViewerField("uid", "uid");
				DetailViewerField nameDetail = new DetailViewerField("name", "name");
				DetailViewerField typeDetail = new DetailViewerField("type", "type");
				DetailViewerField publicStateDetail = new DetailViewerField("publicState", "publicState");
				DetailViewerField persistentDetail = new DetailViewerField("persistent", "persistent");
				DetailViewerField regtimeDetail = new DetailViewerField("regtime", "regtime");
				DetailViewerField sourceDetail = new DetailViewerField("source", "source");
				DetailViewerField stateDetail = new DetailViewerField("state", "state");
				DetailViewerField running_vmsDetail = new DetailViewerField("running_vms", "running_vms");

				details.setFields(idFieldDetail, uidDetail, nameDetail, typeDetail, publicStateDetail, persistentDetail, regtimeDetail, sourceDetail,
						stateDetail, running_vmsDetail);

			}

			public void onFailure(Throwable arg0) {
				// TODO Auto-generated method stub
			}
		});
	}

}
